package org.jeecg.modules.demo.dtwlwjc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.demo.dtwlwjc.entity.ZwglPestCount;
import org.jeecg.modules.demo.dtwlwjc.mapper.ZwglPestCountMapper;
import org.jeecg.modules.demo.dtwlwjc.service.IZwglPestCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 病虫计数
 * @Author: jeecg-boot
 * @Date: 2023-04-17
 * @Version: V1.0
 */
@Service
public class ZwglPestCountServiceImpl extends ServiceImpl<ZwglPestCountMapper, ZwglPestCount> implements IZwglPestCountService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ZwglPestCountMapper zwglPestCountMapper;


    @Override
    public Result<List<Map>> findPestRangCount(String startDate, String endDate) {
        List<Map> mDatas = zwglPestCountMapper.findPestRangCount(startDate, endDate);
        return Result.OK(mDatas);
    }

    @Override
    public String getToken() {
        final String CONTENT_TYPE_TEXT_JSON = "text/json";
        DefaultHttpClient client = new DefaultHttpClient(
                new PoolingClientConnectionManager());

        String url = "http://farm.0531yun.cn/customUser/Login";
        String js = "{\"loginName\":\"blkj\",\"loginPwd\":\"blkj\"}";

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

        StringEntity se = null;
        try {
            se = new StringEntity(js);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);

        CloseableHttpResponse response2 = null;

        try {
            response2 = client.execute(httpPost);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity entity2 = null;
        entity2 = response2.getEntity();
        String s2 = null;
        try {
            s2 = EntityUtils.toString(entity2, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        JSONObject jsonObject = JSON.parseObject(s2);

        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
        String token = jsonObject1.getString("token");

        redisUtil.set("dttoken", token, 7200);
        return null;
    }

    @Override
    public String getdtsj() {
        String[] arr;
        arr = new String[12];
        arr[0] = "0511220007";
        arr[1] = "0512220003";
        arr[2] = "0511220001";
        arr[3] = "0511220008";
        arr[4] = "0511220006";
        arr[5] = "0514220002";
        arr[6] = "0512220005";
        arr[7] = "0512220006";
        arr[8] = "0514220001";
        arr[9] = "0514220004";
        arr[10] = "0511220002";
        arr[11] = "0511220003";
        for (int i = 0; i < arr.length; i++) {

            //得到long类型当前时间
            long l = System.currentTimeMillis();
            //new日期对象
            Date date = new Date(l);
            Date date1 = new Date(l);
            //转换提日期输出格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(date);
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time1 = dateFormat1.format(date1);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            //调用的api的接口地址
            String deviceAddr = arr[i];
            String startTime = dateFormat.format(calendar.getTime());
//            String startTime = "2023-08-27";
            String endTime = time;
            String apiPath = "http://farm.0531yun.cn/UserDevice/WormAnalyzeReport?deviceAddr=" + deviceAddr + "&startTime=" + startTime + "&endTime=" + endTime;


            BufferedReader in = null;
            StringBuffer result = null;
            String token = (String) redisUtil.get("dttoken");

            if (Objects.isNull(token)) {
                getToken();

            }

            try {
                URL url = new URL(apiPath);
                //打开和url之间的连接

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);


                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("token", token);
                connection.setRequestProperty("Charset", "utf-8");
                connection.connect();
                result = new StringBuffer();
                //读取URL的响应
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                String result2 = result.toString(); //返回json字符串

                //获取数据
                JSONObject jsonObject = JSON.parseObject(result2);

                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(j);
                    JSONObject jsonObject2=jsonObject1.getJSONObject("wormDataAIDO");
                    JSONArray jsonArray1 = jsonObject2.getJSONArray("analyseData");
                    for (int k = 0; k < jsonArray1.size(); k++) {
                        JSONObject jsonObject3 = jsonArray1.getJSONObject(k);
                        ZwglPestCount zwglPestCount=new ZwglPestCount();
                        zwglPestCount.setDeviceAdNum(jsonObject1.getString("deviceAddr"));
                        zwglPestCount.setDeviceName(jsonObject1.getString("deviceName"));
                        zwglPestCount.setDeviceTime(time1);
                        zwglPestCount.setPestName(jsonObject3.getString("name"));
                        zwglPestCount.setPestCount(jsonObject3.getInteger("num"));
                        zwglPestCountMapper.insert(zwglPestCount);

                    }


                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
        return null;
    }


}
